#define _SVID_SOURCE  1
#include <header.h>


/**
 * @bug 传输有问题
*/
int main(int argc, char* argv[]){
	int socket_pair_fd[2];
	socketpair(AF_LOCAL, SOCK_STREAM, 0, socket_pair_fd);

	if(fork() == 0){
		// child
		// read 0
		close(socket_pair_fd[1]);

		struct msghdr msg;
		__bzero(&msg, sizeof msg);

		char buf[1024];
		struct iovec iovs[1];
		iovs[0].iov_base = buf;
		iovs[0].iov_len = sizeof(buf);

		msg.msg_iov = iovs;
		msg.msg_iovlen = 1;

		struct cmsghdr *cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
		cms->cmsg_len = CMSG_LEN(sizeof(int));
		cms->cmsg_level = SOL_SOCKET;
		cms->cmsg_type = SCM_RIGHTS;

		msg.msg_control = cms;
		msg.msg_controllen = CMSG_LEN(sizeof(int));

		int ret = recvmsg(socket_pair_fd[0], &msg, 0);
		ERROR_CHECK(ret, -1, "recvmsg");

		void *p =CMSG_DATA(cms);
		int *p_net_fd = (int*)p;

		printf("son: net_fd:%d\n", *p_net_fd);

		send(*p_net_fd, "hello", 5, 0);

	}else{
		// parent
		// write 1
		close(socket_pair_fd[0]);

		int socket_fd = socket(AF_INET, SOCK_STREAM, 0);

		char *port = "8080";
		char *ip = "192.168.169.128";
		struct sockaddr_in server_addr;
		server_addr.sin_family = AF_INET;
		server_addr.sin_port = htons(atoi(port));
		server_addr.sin_addr.s_addr = inet_addr(ip);
		bind(socket_fd, (struct sockaddr*)&server_addr, sizeof server_addr);
		listen(socket_fd, 15);

		int net_fd = accept(socket_fd, NULL, NULL);

		struct msghdr msg;
		__bzero(&msg, sizeof msg);

		char *str = "hello";
		struct iovec iovs[1];
		iovs[0].iov_base = str;
		iovs[0].iov_len = strlen(str);

		msg.msg_iov = iovs;
		msg.msg_iovlen = 1;

		struct cmsghdr *cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
		cms->cmsg_len = CMSG_LEN(sizeof(int));
		cms->cmsg_level = SOL_SOCKET;
		cms->cmsg_type = SCM_RIGHTS;
		void *p = CMSG_DATA(cms);
		int *pfd = (int *)p;
		*pfd = net_fd;

		msg.msg_control = cms;
		msg.msg_controllen = CMSG_LEN(sizeof(int));

		int ret = sendmsg(socket_pair_fd[1], &msg, 0);
		ERROR_CHECK(ret, -1, "sendmsg");
	}

	return 0;
}